package com.atguigu.gulimall.member.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @program: gulimall
 * @description: TODO
 * @author: YuWenYi
 * @create: 2021-07-18 22:17
 **/
@Configuration
public class GuliFeignConfig {

    @Bean
    RequestInterceptor requestInterceptor(){
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate template) {
                //获取当前请求上下文的所有请求属性,本质也就是ThreadLocal
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if (requestAttributes != null){
                    //真的牛!!  获取网页发送过来的请求!  --> 老请求
                    HttpServletRequest request = requestAttributes.getRequest();
                    String cookie = request.getHeader("Cookie");
                    //新请求模板:template  同步老请求中的cookie!
                    template.header("Cookie",cookie);
                }
            }
        };
    }
}
